﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Hongsh.Pay.Client.Proxy.Http;
using MapleLeaf.Pay;
using MapleLeaf.Pay.Pay;
using MapleLeaf.Pay.Trade;

namespace Hongsh.Pay.Client.Proxy.Handlers {
    // Token: 0x0200008B RID: 139
    public static class XLPayProxy {
        // Token: 0x06000509 RID: 1289 RVA: 0x00010C68 File Offset: 0x0000EE68
        public static void AddXLPayProxyHandler(this HttpServer svr) {
            svr.RouterList.Add("GET/wupay.asmx", delegate (HttpContext ctx) {
                ctx.Result = HttpResult.Ok;
            });
            svr.RouterList.Add("POST/wupay.asmx", new HttpContextActionDelegate(Process));
            svr.RouterList.Add("POST/wupay.asmx/Pay", new HttpContextActionDelegate(Pay));
            svr.RouterList.Add("POST/wupay.asmx/Refund", new HttpContextActionDelegate(Refund));
            svr.RouterList.Add("POST/wupay.asmx/Inquire", new HttpContextActionDelegate(Inquire));
        }

        // Token: 0x0600050A RID: 1290 RVA: 0x00010D14 File Offset: 0x0000EF14
        private static void Pay(HttpContext ctx) {
            XiLianPayReqeust req = new XiLianPayReqeust {
                money = int.Parse(ctx.Request.Form["money"]),
                auth_code = ctx.Request.Form["auth_code"],
                order_id = ctx.Request.Form["order_id"],
                goods_info = ctx.Request.Form["goods_info"]
            };
            Process(ctx, req, "Pay");
        }

        // Token: 0x0600050B RID: 1291 RVA: 0x00010DA4 File Offset: 0x0000EFA4
        private static void Refund(HttpContext ctx) {
            XiLianPayReqeust req = new XiLianPayReqeust {
                refund_fee = int.Parse(ctx.Request.Form["refund_fee"]),
                pay_nd = ctx.Request.Form["pay_nd"],
                order_id = ctx.Request.Form["order_id"],
                refund_id = ctx.Request.Form["refund_id"]
            };
            Process(ctx, req, "Refund");
        }

        // Token: 0x0600050C RID: 1292 RVA: 0x00010E34 File Offset: 0x0000F034
        private static void Inquire(HttpContext ctx) {
            XiLianPayReqeust req = new XiLianPayReqeust {
                pay_nd = ctx.Request.Form["pay_nd"],
                order_id = ctx.Request.Form["order_id"]
            };
            Process(ctx, req, "Inquire");
        }

        // Token: 0x0600050D RID: 1293 RVA: 0x00010E8C File Offset: 0x0000F08C
        private static HttpResult GetResult(object result, object action) {
            string text = "<WU_ROOT><HEAD xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/><BODY>" + HongshExtends.ToXElement(result, "RETURN_DATA").ToString(SaveOptions.DisableFormatting) + "</BODY></WU_ROOT>";
            StringBuilder stringBuilder = new StringBuilder().Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").Append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">").Append("<soap:Body>").AppendFormat("<{0}Response xmlns=\"http://tempuri.org/\">", action).AppendFormat("<{0}Result>", action).Append(text.Replace("<", "&lt;").Replace(">", "&gt;")).AppendFormat("</{0}Result>", action).AppendFormat("</{0}Response>", action).Append("</soap:Body>").Append("</soap:Envelope>");
            return new HttpTextResult(stringBuilder.ToString(), "text/xml");
        }

        // Token: 0x0600050E RID: 1294 RVA: 0x00010F54 File Offset: 0x0000F154
        private static void Process(HttpContext ctx) {
            string action = ctx.Request.Header["SOAPAction"].Trim(new char[]
            {
                '"'
            }).Substring(19);
            string s = new StreamReader(ctx.Request).ReadToEnd();
            string text = System.Web.HttpUtility.HtmlDecode(s).Replace("m:", "");
            text = text.Replace("xmlns=\"http://tempuri.org/\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
            XElement src = text.smethod_2().Elements().First().Elements().First();
            XiLianPayReqeust req = src.ToObject<XiLianPayReqeust>();
            Process(ctx, req, action);
        }

        // Token: 0x0600050F RID: 1295 RVA: 0x00010FF4 File Offset: 0x0000F1F4
        private static void Process(HttpContext ctx, XiLianPayReqeust req, string action) {
            DateTime now = DateTime.Now;
            XiLianPayResult xiLianPayResult = null;
            try {
                if (action == "Refund") {
                    HongshPayTrade hongshPayTrade = ctx.Execute(new TradeRefundRequest {
                        RefundAmount = req.refund_fee,
                        TradeId = req.pay_nd,
                        ClientTradeId = req.order_id,
                        ClientRefundTradeId = req.refund_id
                    });
                    if (hongshPayTrade.State == TradeState.关闭 || hongshPayTrade.State == TradeState.失败) {
                        throw new Exception("退款失败：" + hongshPayTrade.StateDescript);
                    }
                    xiLianPayResult = new XilianRefundResult {
                        pay_nd = hongshPayTrade.TradeId,
                        order_id = req.order_id
                    };
                    if (hongshPayTrade.State == TradeState.成功) {
                        xiLianPayResult.return_code = "SUCCESS";
                        xiLianPayResult.return_msg = "退款成功";
                        (xiLianPayResult as XilianRefundResult).refund_fee = hongshPayTrade.Amount * 100;
                    }
                    else {
                        xiLianPayResult.return_code = "USER_PAYING";
                        xiLianPayResult.return_msg = "退款处理中";
                    }
                }
                else {
                    HongshPayTrade hongshPayTrade2;
                    if (action == "Pay" || action == "PayV2") {
                        TradeAuthPaymentRequest tradeAuthPaymentRequest = new TradeAuthPaymentRequest {
                            Amount = req.money,
                            Subject = req.order_id,
                            Authcode = req.auth_code,
                            ClientTradeId = req.order_id
                        };
                        try {
                            XiLianGoodInfo[] source = req.goods_info.JsonDecode<XiLianGoodInfo[]>();
                            tradeAuthPaymentRequest.GoodsList = (from d in source
                                                                 select new TradeGoods {
                                                                     Id = d.goods_id,
                                                                     Name = d.goods_name,
                                                                     Price = (int)(d.price * 100m),
                                                                     Quantity = d.quantity
                                                                 }).ToArray<TradeGoods>();
                        }
                        catch {
                        }
                        hongshPayTrade2 = ctx.Execute(tradeAuthPaymentRequest);
                        req.pay_nd = hongshPayTrade2.TradeId;
                        while (hongshPayTrade2.State == TradeState.未知 && DateTime.Now.Subtract(now).TotalSeconds < 100.0) {
                            hongshPayTrade2 = ctx.Execute(new TradePaymentQueryRequest {
                                TradeId = req.pay_nd,
                                ClientTradeId = req.order_id
                            });
                        }
                    }
                    else {
                        if (!(action == "Inquire")) {
                            throw new Exception("不支持的服务接口！");
                        }
                        hongshPayTrade2 = ctx.Execute(new TradePaymentQueryRequest {
                            TradeId = req.pay_nd,
                            ClientTradeId = req.order_id
                        });
                    }
                    if (hongshPayTrade2.State == TradeState.失败) {
                        throw new Exception("交易失败，请撤销交易！");
                    }
                    if (hongshPayTrade2.State == TradeState.关闭) {
                        throw new Exception("交易已关闭！");
                    }
                    if (hongshPayTrade2.State == TradeState.成功) {
                        int port = ctx.Request.Connection.LocalEndPoint.Port;
                        xiLianPayResult = new XiLianAuthPaymentResult {
                            order_id = req.order_id,
                            pay_nd = hongshPayTrade2.TradeId,
                            return_code = "SUCCESS",
                            user_id = hongshPayTrade2.Payer,
                            payment = hongshPayTrade2.Payway.ToString(),
                            pay_info = hongshPayTrade2.Amount.ToString(),
                            money = (port == 9999) ? (hongshPayTrade2.Amount / 100m).ToString("0.00") : hongshPayTrade2.Amount.ToString(),
                            pay_detail = (port == 9999) ? null : ("{ \"0\" : { \"type\" : 1, \"code\" : \"0\", \"name\" : \"现金\", \"money\" : " + hongshPayTrade2.ActualAmount.ToString() + " } }")
                        };
                    }
                    else {
                        xiLianPayResult = new XilianPayingResult {
                            return_code = "USER_PAYING",
                            return_msg = "等待用户处理中",
                            pay_nd = hongshPayTrade2.TradeId,
                            order_id = req.order_id
                        };
                    }
                }
            }
            catch (Exception ex) {
                xiLianPayResult = new XiLianPayResult {
                    return_code = "SYSTEM_ERROR",
                    return_msg = ex.Message
                };
            }
            ctx.Result = GetResult(xiLianPayResult, action);
        }
    }
}
